#include "spectrumexporter.h"
#include <QFile>
#include <QDebug>
#include <QDateTime>
#include "tev/tevampspectrum.h"
#include "prps/prpdspectrum.h"
#include "prps/prpsspectrum.h"
#include "ae/aeampspectrum.h"
#include "ae/aephasespectrum.h"
#include "ae/aepulsespectrum.h"
#include "ae/aewavespectrum.h"
#include "infrared/infraredspectrum.h"
#include "spectrumfactory.h"

// 添加csv库头文件
#include "stringdata.h"
#include "writer.h"

SpectrumExporter::SpectrumExporter(QObject* parent)
    : QObject(parent)
{
    initDefaultHandlers();
}

SpectrumExporter::~SpectrumExporter()
{
}

void SpectrumExporter::registerExportHandler(int spectrumTypeCode, 
    std::function<bool(QTextStream&, DataSpecificationGW::Spectrum*)> handler)
{
    m_exportHandlers[spectrumTypeCode] = handler;
}

bool SpectrumExporter::exportTEVAmpSpectrum(QTextStream& out, DataSpecificationGW::Spectrum* spectrum)
{
    // 转换为TEV幅值图谱
    DataSpecificationGW::TEVAmpSpectrum* tevAmpSpectrum = 
        dynamic_cast<DataSpecificationGW::TEVAmpSpectrum*>(spectrum);
    
    if (!tevAmpSpectrum) {
        out << "# 错误: 图谱类型转换失败\n";
        return false;
    }
    
    // 获取TEV幅值扩展信息
    DataSpecificationGW::TEVAmpExtInformation extInfo;
    tevAmpSpectrum->getTEVAmpExtInformation(extInfo);
    
    // 导出TEV幅值特有信息
    out << "### TEV幅值特有信息\n";
    out << "幅值单位,幅值下限,幅值上限\n";
    out << QString("%1,%2,%3\n\n")
           .arg(escapeCSVField(QString::number(static_cast<int>(extInfo.eAmpUnit))))
           .arg(escapeCSVField(QString::number(extInfo.fAmpLowerLimit)))
           .arg(escapeCSVField(QString::number(extInfo.fAmpUpperLimit)));
    
    // 获取TEV幅值数据
    DataSpecificationGW::TEVAmpData tevData;
    tevAmpSpectrum->getTEVAmpData(tevData);
    
    // 导出TEV幅值数据
    out << "### TEV幅值数据\n";
    out << "TEV幅值,TEV最大值,脉冲数,严重程度,背景文件名,报警等级\n";
    out << QString("%1,%2,%3,%4,%5,%6\n")
           .arg(escapeCSVField(QString::number(tevData.fTEVAmpValue)))
           .arg(escapeCSVField(QString::number(tevData.fTEVMaxValue)))
           .arg(escapeCSVField(QString::number(tevData.iPulseCount)))
           .arg(escapeCSVField(QString::number(tevData.fSeverity)))
           .arg(escapeCSVField(tevData.qstrBGFileName))
           .arg(escapeCSVField(QString::number(static_cast<int>(tevData.eDischargeSeverity))));
    
    return true;
}

bool SpectrumExporter::exportPRPDSpectrum(QTextStream& out, DataSpecificationGW::Spectrum* spectrum)
{
    // 转换为PRPD图谱
    DataSpecificationGW::PRPDSpectrum* prpdSpectrum = 
        dynamic_cast<DataSpecificationGW::PRPDSpectrum*>(spectrum);
    
    if (!prpdSpectrum) {
        out << "# 错误: 图谱类型转换失败\n";
        return false;
    }
    
    // 获取PRPD扩展信息
    DataSpecificationGW::PRPDExtInformation extInfo;
    prpdSpectrum->getPRPDExtInformation(extInfo);
    
    // 导出PRPD特有信息
    out << "### PRPD特有信息\n";
    out << "幅值单位,幅值下限,幅值上限,频带,频率下限,频率上限,相位窗数,量化幅值,工频周期数\n";
    out << QString("%1,%2,%3,%4,%5,%6,%7,%8,%9\n\n")
           .arg(escapeCSVField(QString::number(static_cast<int>(extInfo.eAmpUnit))))
           .arg(escapeCSVField(QString::number(extInfo.fAmpLowerLimit)))
           .arg(escapeCSVField(QString::number(extInfo.fAmpUpperLimit)))
           .arg(escapeCSVField(QString::number(static_cast<int>(extInfo.eFrequencyBand))))
           .arg(escapeCSVField(QString::number(extInfo.fFrequencyLowerLimit)))
           .arg(escapeCSVField(QString::number(extInfo.fFequencyUpperLimit)))
           .arg(escapeCSVField(QString::number(extInfo.iPhaseWindowCount)))
           .arg(escapeCSVField(QString::number(extInfo.iQuantizedAmplitude)))
           .arg(escapeCSVField(QString::number(extInfo.iPowerFreqCycleCount)));
    
    // 导出放电类型概率
    out << "### 放电类型概率\n";
    out << "类型1,类型2,类型3,类型4,类型5,类型6,类型7,类型8\n";
    out << QString("%1,%2,%3,%4,%5,%6,%7,%8\n\n")
           .arg(escapeCSVField(QString::number(extInfo.aucPDTypeProbability[0])))
           .arg(escapeCSVField(QString::number(extInfo.aucPDTypeProbability[1])))
           .arg(escapeCSVField(QString::number(extInfo.aucPDTypeProbability[2])))
           .arg(escapeCSVField(QString::number(extInfo.aucPDTypeProbability[3])))
           .arg(escapeCSVField(QString::number(extInfo.aucPDTypeProbability[4])))
           .arg(escapeCSVField(QString::number(extInfo.aucPDTypeProbability[5])))
           .arg(escapeCSVField(QString::number(extInfo.aucPDTypeProbability[6])))
           .arg(escapeCSVField(QString::number(extInfo.aucPDTypeProbability[7])));
    
    // 导出其他信息
    out << "### 其他信息\n";
    out << "背景文件名,数据判断标志,增益,同步源,同步状态,同步频率,报警等级,去噪阈值\n";
    out << QString("%1,%2,%3,%4,%5,%6,%7,%8\n\n")
           .arg(escapeCSVField(extInfo.qstrBGFileName))
           .arg(escapeCSVField(QString::number(static_cast<int>(extInfo.eDataJudgmentFlag))))
           .arg(escapeCSVField(QString::number(extInfo.sGain)))
           .arg(escapeCSVField(QString::number(static_cast<int>(extInfo.eSyncSource))))
           .arg(escapeCSVField(QString::number(extInfo.ucSyncState)))
           .arg(escapeCSVField(QString::number(extInfo.fSyncFrequency)))
           .arg(escapeCSVField(QString::number(static_cast<int>(extInfo.eDischargeSeverity))))
           .arg(escapeCSVField(QString::number(extInfo.ucDenoisingThreshold)));
    
    // 获取PRPD数据
    DataSpecificationGW::PRPDData prpdData;
    prpdSpectrum->getPRPDData(prpdData);
    
    // 导出PRPD数据
    out << "### PRPD数据 (二进制数据摘要)\n";
    out << "数据大小: " << prpdData.qbaPDSpectrumData.size() << " 字节\n";
    
    // 为了导出的CSV可读性，只导出部分二进制数据的十六进制表示
    if (!prpdData.qbaPDSpectrumData.isEmpty()) {
        out << "前50字节十六进制表示:\n";
        out << escapeCSVField(binaryToHexString(prpdData.qbaPDSpectrumData)) << "\n";
    } else {
        out << "# 无PRPD数据\n";
    }
    
    return true;
}

bool SpectrumExporter::exportPRPSSpectrum(QTextStream& out, DataSpecificationGW::Spectrum* spectrum)
{
    // 转换为PRPS图谱
    DataSpecificationGW::PRPSSpectrum* prpsSpectrum = 
        dynamic_cast<DataSpecificationGW::PRPSSpectrum*>(spectrum);
    
    if (!prpsSpectrum) {
        out << "# 错误: 图谱类型转换失败\n";
        return false;
    }
    
    // 获取PRPS扩展信息
    DataSpecificationGW::PRPSExtInformation extInfo;
    prpsSpectrum->getPRPSExtInformation(extInfo);
    
    // 导出PRPS特有信息
    out << "### PRPS特有信息\n";
    out << "幅值单位,幅值下限,幅值上限,频带,频率下限,频率上限,相位窗数,量化幅值,工频周期数\n";
    out << QString("%1,%2,%3,%4,%5,%6,%7,%8,%9\n\n")
           .arg(escapeCSVField(QString::number(static_cast<int>(extInfo.eAmpUnit))))
           .arg(escapeCSVField(QString::number(extInfo.fAmpLowerLimit)))
           .arg(escapeCSVField(QString::number(extInfo.fAmpUpperLimit)))
           .arg(escapeCSVField(QString::number(static_cast<int>(extInfo.eFrequencyBand))))
           .arg(escapeCSVField(QString::number(extInfo.fFrequencyLowerLimit)))
           .arg(escapeCSVField(QString::number(extInfo.fFequencyUpperLimit)))
           .arg(escapeCSVField(QString::number(extInfo.iPhaseWindowCount)))
           .arg(escapeCSVField(QString::number(extInfo.iQuantizedAmplitude)))
           .arg(escapeCSVField(QString::number(extInfo.iPowerFreqCycleCount)));
    
    // 导出放电类型概率
    out << "### 放电类型概率\n";
    out << "类型1,类型2,类型3,类型4,类型5,类型6,类型7,类型8\n";
    out << QString("%1,%2,%3,%4,%5,%6,%7,%8\n\n")
           .arg(escapeCSVField(QString::number(extInfo.aucPDTypeProbability[0])))
           .arg(escapeCSVField(QString::number(extInfo.aucPDTypeProbability[1])))
           .arg(escapeCSVField(QString::number(extInfo.aucPDTypeProbability[2])))
           .arg(escapeCSVField(QString::number(extInfo.aucPDTypeProbability[3])))
           .arg(escapeCSVField(QString::number(extInfo.aucPDTypeProbability[4])))
           .arg(escapeCSVField(QString::number(extInfo.aucPDTypeProbability[5])))
           .arg(escapeCSVField(QString::number(extInfo.aucPDTypeProbability[6])))
           .arg(escapeCSVField(QString::number(extInfo.aucPDTypeProbability[7])));
    
    // 导出其他信息
    out << "### 其他信息\n";
    out << "背景文件名,数据判断标志,增益,同步源,同步状态,同步频率,报警等级,去噪阈值\n";
    out << QString("%1,%2,%3,%4,%5,%6,%7,%8\n\n")
           .arg(escapeCSVField(extInfo.qstrBGFileName))
           .arg(escapeCSVField(QString::number(static_cast<int>(extInfo.eDataJudgmentFlag))))
           .arg(escapeCSVField(QString::number(extInfo.sGain)))
           .arg(escapeCSVField(QString::number(static_cast<int>(extInfo.eSyncSource))))
           .arg(escapeCSVField(QString::number(extInfo.ucSyncState)))
           .arg(escapeCSVField(QString::number(extInfo.fSyncFrequency)))
           .arg(escapeCSVField(QString::number(static_cast<int>(extInfo.eDischargeSeverity))))
           .arg(escapeCSVField(QString::number(extInfo.ucDenoisingThreshold)));
    
    // 获取PRPS数据
    DataSpecificationGW::PRPSData prpsData;
    prpsSpectrum->getPRPSData(prpsData);
    
    // 导出PRPS数据
    out << "### PRPS数据 (二进制数据摘要)\n";
    out << "数据大小: " << prpsData.qbaPDSpectrumData.size() << " 字节\n";
    
    // 为了导出的CSV可读性，只导出部分二进制数据的十六进制表示
    if (!prpsData.qbaPDSpectrumData.isEmpty()) {
        out << "前50字节十六进制表示:\n";
        out << escapeCSVField(binaryToHexString(prpsData.qbaPDSpectrumData)) << "\n";
    } else {
        out << "# 无PRPS数据\n";
    }
    
    return true;
}

bool SpectrumExporter::exportAEAmpSpectrum(QTextStream& out, DataSpecificationGW::Spectrum* spectrum)
{
    // 转换为AE幅值图谱
    DataSpecificationGW::AEAmpSpectrum* aeAmpSpectrum = 
        dynamic_cast<DataSpecificationGW::AEAmpSpectrum*>(spectrum);
    
    if (!aeAmpSpectrum) {
        out << "# 错误: 图谱类型转换失败\n";
        return false;
    }
    
    // 获取AE幅值扩展信息
    DataSpecificationGW::AEAmpExtInformation extInfo;
    aeAmpSpectrum->getAEAmpExtInformation(extInfo);
    
    // 导出AE幅值特有信息
    out << "### AE幅值特有信息\n";
    out << "幅值单位,幅值下限,幅值上限,频带,频率下限,频率上限\n";
    out << QString("%1,%2,%3,%4,%5,%6\n\n")
           .arg(escapeCSVField(QString::number(static_cast<int>(extInfo.eAmpUnit))))
           .arg(escapeCSVField(QString::number(extInfo.fAmpLowerLimit)))
           .arg(escapeCSVField(QString::number(extInfo.fAmpUpperLimit)))
           .arg(escapeCSVField(QString::number(static_cast<int>(extInfo.eFrequencyBand))))
           .arg(escapeCSVField(QString::number(extInfo.fFrequencyLowerLimit)))
           .arg(escapeCSVField(QString::number(extInfo.fFequencyUpperLimit)));
    
    // 获取AE幅值数据
    DataSpecificationGW::AEAmpData aeData;
    aeAmpSpectrum->getAEAmpData(aeData);
    
    // 导出AE幅值数据
    out << "### AE幅值数据\n";
    out << "信号最大值,信号有效值,频率分量1,频率分量2,背景信号最大值,背景信号有效值,背景频率分量1,背景频率分量2\n";
    out << QString("%1,%2,%3,%4,%5,%6,%7,%8\n")
           .arg(escapeCSVField(QString::number(aeData.fSignalMax)))
           .arg(escapeCSVField(QString::number(aeData.fSignalRMS)))
           .arg(escapeCSVField(QString::number(aeData.fFrequencyComponent1)))
           .arg(escapeCSVField(QString::number(aeData.fFrequencyComponent2)))
           .arg(escapeCSVField(QString::number(aeData.fBGSignalMax)))
           .arg(escapeCSVField(QString::number(aeData.fBGSignalRMS)))
           .arg(escapeCSVField(QString::number(aeData.fBGFrequencyComponent1)))
           .arg(escapeCSVField(QString::number(aeData.fBGFrequencyComponent2)));
    
    return true;
}

bool SpectrumExporter::exportAEPhaseSpectrum(QTextStream& out, DataSpecificationGW::Spectrum* spectrum)
{
    // 转换为AE相位图谱
    DataSpecificationGW::AEPhaseSpectrum* aePhaseSpectrum = 
        dynamic_cast<DataSpecificationGW::AEPhaseSpectrum*>(spectrum);
    
    if (!aePhaseSpectrum) {
        out << "# 错误: 图谱类型转换失败\n";
        return false;
    }
    
    // 获取AE相位扩展信息
    DataSpecificationGW::AEPhaseExtInformation extInfo;
    aePhaseSpectrum->getAEPhaseExtInformation(extInfo);
    
    // 导出AE相位特有信息
    out << "### AE相位特有信息\n";
    out << "幅值单位,幅值下限,幅值上限,相位窗数,量化幅值,同步频率\n";
    out << QString("%1,%2,%3,%4,%5,%6\n\n")
           .arg(escapeCSVField(QString::number(static_cast<int>(extInfo.eAmpUnit))))
           .arg(escapeCSVField(QString::number(extInfo.fAmpLowerLimit)))
           .arg(escapeCSVField(QString::number(extInfo.fAmpUpperLimit)))
           .arg(escapeCSVField(QString::number(extInfo.iDataPoint)))
           .arg(escapeCSVField(QString::number(extInfo.fTriggerThreshold)))
           .arg(escapeCSVField(QString::number(extInfo.fSyncFrequency)));
    
    // 获取AE相位数据
    DataSpecificationGW::AEPhaseData aeData;
    aePhaseSpectrum->getAEPhaseData(aeData);
    
    // 导出AE相位数据
    out << "### AE相位数据\n";
    out << "相位数据大小: " << aeData.qbaAEPhaseData.size() << " 字节\n";
    
    // 为了导出的CSV可读性，只导出部分二进制数据的十六进制表示
    if (!aeData.qbaAEPhaseData.isEmpty()) {
        out << "前50字节十六进制表示:\n";
        const int maxBytesToShow = qMin(50, aeData.qbaAEPhaseData.size());
        QString hexData;
        for (int i = 0; i < maxBytesToShow; i++) {
            hexData += QString("%1 ").arg((quint8)aeData.qbaAEPhaseData.at(i), 2, 16, QChar('0'));
        }
        out << escapeCSVField(hexData) << "\n";
    } else {
        out << "# 无AE相位数据\n";
    }
    
    return true;
}

bool SpectrumExporter::exportAEPulseSpectrum(QTextStream& out, DataSpecificationGW::Spectrum* spectrum)
{
    // 转换为AE脉冲图谱
    DataSpecificationGW::AEPulseSpectrum* aePulseSpectrum = 
        dynamic_cast<DataSpecificationGW::AEPulseSpectrum*>(spectrum);
    
    if (!aePulseSpectrum) {
        out << "# 错误: 图谱类型转换失败\n";
        return false;
    }
    
    // 获取AE脉冲扩展信息
    DataSpecificationGW::AEPulseExtInformation extInfo;
    aePulseSpectrum->getAEPulseExtInformation(extInfo);
    
    // 导出AE脉冲特有信息
    out << "### AE脉冲特有信息\n";
    out << "幅值单位,幅值下限,幅值上限,脉冲数,量化幅值\n";
    out << QString("%1,%2,%3,%4,%5\n\n")
           .arg(escapeCSVField(QString::number(static_cast<int>(extInfo.eAmpUnit))))
           .arg(escapeCSVField(QString::number(extInfo.fAmpLowerLimit)))
           .arg(escapeCSVField(QString::number(extInfo.fAmpUpperLimit)))
           .arg(escapeCSVField(QString::number(extInfo.iDataPoint)))
           .arg(escapeCSVField(QString::number(extInfo.fTriggerThreshold)));
    
    // 获取AE脉冲数据
    DataSpecificationGW::AEPulseData aeData;
    aePulseSpectrum->getAEPulseData(aeData);
    
    // 导出AE脉冲数据
    out << "### AE脉冲数据\n";
    out << "脉冲数据大小: " << aeData.qbaAEPulseData.size() << " 字节\n";
    
    // 为了导出的CSV可读性，只导出部分二进制数据的十六进制表示
    if (!aeData.qbaAEPulseData.isEmpty()) {
        out << "前50字节十六进制表示:\n";
        const int maxBytesToShow = qMin(50, aeData.qbaAEPulseData.size());
        QString hexData;
        for (int i = 0; i < maxBytesToShow; i++) {
            hexData += QString("%1 ").arg((quint8)aeData.qbaAEPulseData.at(i), 2, 16, QChar('0'));
        }
        out << escapeCSVField(hexData) << "\n";
    } else {
        out << "# 无AE脉冲数据\n";
    }
    
    return true;
}

bool SpectrumExporter::exportAEWaveSpectrum(QTextStream& out, DataSpecificationGW::Spectrum* spectrum)
{
    // 转换为AE波形图谱
    DataSpecificationGW::AEWaveSpectrum* aeWaveSpectrum = 
        dynamic_cast<DataSpecificationGW::AEWaveSpectrum*>(spectrum);
    
    if (!aeWaveSpectrum) {
        out << "# 错误: 图谱类型转换失败\n";
        return false;
    }
    
    // 获取AE波形扩展信息
    DataSpecificationGW::AEWaveExtInformation extInfo;
    aeWaveSpectrum->getAEWaveExtInformation(extInfo);
    
    // 导出AE波形特有信息
    out << "### AE波形特有信息\n";
    out << "采样率,采样点数,量化位数,同步频率\n";
    out << QString("%1,%2,%3,%4\n\n")
           .arg(escapeCSVField(QString::number(extInfo.llSampleRate)))
           .arg(escapeCSVField(QString::number(extInfo.iDataPoint)))
           .arg(escapeCSVField(QString::number(extInfo.fTriggerThreshold)))
           .arg(escapeCSVField(QString::number(extInfo.fSyncFrequency)));
    
    // 获取AE波形数据
    DataSpecificationGW::AEWaveData aeData;
    aeWaveSpectrum->getAEWaveData(aeData);
    
    // 导出AE波形数据
    out << "### AE波形数据\n";
    out << "波形数据大小: " << aeData.qbaAEWaveData.size() << " 字节\n";
    
    // 为了导出的CSV可读性，只导出部分二进制数据的十六进制表示
    if (!aeData.qbaAEWaveData.isEmpty()) {
        out << "前50字节十六进制表示:\n";
        out << escapeCSVField(binaryToHexString(aeData.qbaAEWaveData)) << "\n";
    } else {
        out << "# 无AE波形数据\n";
    }
    
    return true;
}

bool SpectrumExporter::exportInfraredSpectrum(QTextStream& out, DataSpecificationGW::Spectrum* spectrum)
{
    // 转换为红外图谱
    DataSpecificationGW::InfraredSpectrum* infraredSpectrum = 
        dynamic_cast<DataSpecificationGW::InfraredSpectrum*>(spectrum);
    
    if (!infraredSpectrum) {
        out << "# 错误: 图谱类型转换失败\n";
        return false;
    }
    
    // 获取红外扩展信息
    DataSpecificationGW::InfraredExtInformation extInfo;
    infraredSpectrum->getInfraredExtInformation(extInfo);
    
    // 导出红外特有信息
    out << "### 红外特有信息\n";
    out << "温度单位,温度下限,温度上限,环境温度,发射率\n";
    out << QString("%1,%2,%3,%4,%5\n\n")
           .arg(escapeCSVField(QString::number(static_cast<int>(extInfo.eTemperatureUnit))))
           .arg(escapeCSVField(QString::number(extInfo.fAtomTemperature)))
           .arg(escapeCSVField(QString::number(extInfo.fAtomTemperature)))
           .arg(escapeCSVField(QString::number(extInfo.fAtomTemperature)))
           .arg(escapeCSVField(QString::number(extInfo.fAtomTemperature)));
    
    // 获取红外数据
    DataSpecificationGW::InfraredData infraredData;
    infraredSpectrum->getInfraredData(infraredData);
    
    // 导出红外数据
    out << "### 红外数据\n";
    out << "红外数据大小: " << infraredData.qbaInfraredPhotoData.size() << " 字节\n";
    
    // 为了导出的CSV可读性，只导出部分二进制数据的十六进制表示
    if (!infraredData.qbaInfraredPhotoData.isEmpty()) {
        out << "前50字节十六进制表示:\n";
        const int maxBytesToShow = qMin(50, infraredData.qbaInfraredPhotoData.size());
        QString hexData;
        for (int i = 0; i < maxBytesToShow; i++) {
            hexData += QString("%1 ").arg((quint8)infraredData.qbaInfraredPhotoData.at(i), 2, 16, QChar('0'));
        }
        out << escapeCSVField(hexData) << "\n";
    } else {
        out << "# 无红外数据\n";
    }
    
    return true;
}

bool SpectrumExporter::exportUnknownSpectrum(QTextStream& out, DataSpecificationGW::Spectrum* spectrum)
{
    if (!spectrum) {
        out << "# 错误: 无效的图谱对象\n";
        return false;
    }
    
    // 获取图谱头信息
    DataSpecificationGW::SpectrumHead head;
    spectrum->getSpectrumHead(head);
    
    // 导出基本信息
    out << "### 未知类型图谱信息\n";
    out << "图谱类型代码: " << static_cast<int>(head.eSpectrumTypeCode) << "\n";
    out << "图谱名称: " << head.qstrSpectrumGenerationTime << "\n";
    out << "图谱描述: " << head.qstrSpectrumGenerationTime << "\n";
    out << "图谱时间: " << formatDateTime(head.qstrSpectrumGenerationTime) << "\n";
    out << "图谱位置: " << head.qstrSpectrumGenerationTime << "\n";
    out << "图谱设备: " << head.qstrSpectrumGenerationTime << "\n";
    out << "图谱通道: " << static_cast<int>(head.eSpectrumCharacter) << "\n";
    out << "图谱单位: " << head.qstrSpectrumGenerationTime << "\n";
    out << "图谱范围: " << head.qstrSpectrumGenerationTime << "\n";
    out << "图谱分辨率: " << head.qstrSpectrumGenerationTime << "\n";
    out << "图谱精度: " << head.qstrSpectrumGenerationTime << "\n";
    out << "图谱校准: " << head.qstrSpectrumGenerationTime << "\n";
    out << "图谱备注: " << head.qstrSpectrumGenerationTime << "\n\n";
    
    return true;
}

bool SpectrumExporter::exportFileHeader(QTextStream& out, DataSpecificationGW::DataSpecification* specification)
{
    if (!specification) {
        return false;
    }
    
    // 获取文件头信息
    DataSpecificationGW::SpectrumDataFileHead fileHead;
    specification->getSpectrumDataFileHead(fileHead);
    
    // 导出文件头信息
    out << "# 图谱数据文件\n";
    out << "数据规范版本: " << specification->dataSpecificationVersion() << "\n";
    out << "图谱数量: " << fileHead.sSpectrumCount << "\n";
    out << "文件创建时间: " << formatDateTime(fileHead.qstrGenerationTime) << "\n";
    out << "站点名称: " << fileHead.qstrStationName << "\n";
    out << "站点编码: " << fileHead.qstrStationCode << "\n";
    out << "仪器制造商: " << fileHead.qstrInstrumentManufacturer << "\n";
    out << "仪器型号: " << fileHead.qstrInstrumentModel << "\n";
    out << "仪器版本: " << fileHead.qstrInstrumentVersion << "\n";
    out << "仪器序列号: " << fileHead.qstrInstrumentSerialNumber << "\n";
    out << "系统频率: " << fileHead.fSystemFrequency << "\n";
    out << "公司代码: " << fileHead.qstrCompanyCode << "\n\n";
    
    return true;
}

bool SpectrumExporter::exportSpectrumHeader(QTextStream& out, DataSpecificationGW::Spectrum* spectrum)
{
    if (!spectrum) {
        return false;
    }
    
    // 获取图谱头信息
    DataSpecificationGW::SpectrumHead head;
    spectrum->getSpectrumHead(head);
    
    // 导出图谱头信息
    out << "### 图谱基本信息\n";
    out << "图谱类型代码: " << static_cast<int>(head.eSpectrumTypeCode) << "\n";
    out << "图谱数据长度: " << head.iSpectrumDataLength << "\n";
    out << "图谱时间: " << formatDateTime(head.qstrSpectrumGenerationTime) << "\n";
    out << "图谱特性: " << static_cast<int>(head.eSpectrumCharacter) << "\n";
    out << "设备名称: " << head.qstrEquipmentName << "\n";
    out << "设备编码: " << head.qstrEquipmentCode << "\n";
    out << "测试点名称: " << head.qstrTestPointName << "\n";
    out << "测试点编码: " << head.qstrTestPointCode << "\n";
    out << "检测通道ID: " << head.sDetectionChannelID << "\n";
    out << "存储数据类型: " << static_cast<int>(head.eStorageDataType) << "\n\n";
    
    return true;
}

QString SpectrumExporter::formatDateTime(const QString& dateTimeStr)
{
    // 如果日期时间字符串为空，返回空字符串
    if (dateTimeStr.isEmpty()) {
        return QString();
    }
    
    // 尝试解析日期时间字符串
    QDateTime dateTime = QDateTime::fromString(dateTimeStr, "yyyy-MM-dd HH:mm:ss");
    if (!dateTime.isValid()) {
        // 尝试其他可能的格式
        dateTime = QDateTime::fromString(dateTimeStr, Qt::ISODate);
    }
    
    if (!dateTime.isValid()) {
        // 如果解析失败，返回原始字符串
        return dateTimeStr;
    }
    
    // 返回格式化的日期时间字符串
    return dateTime.toString("yyyy-MM-dd HH:mm:ss");
}

void SpectrumExporter::initDefaultHandlers()
{
    // 注册默认的导出处理器
    registerExportHandler(DataSpecificationGW::SPECTRUM_CODE_AE_AMP, 
                         std::bind(&SpectrumExporter::exportAEAmpSpectrum, this, std::placeholders::_1, std::placeholders::_2));
    registerExportHandler(DataSpecificationGW::SPECTRUM_CODE_AE_PHASE,
                         std::bind(&SpectrumExporter::exportAEPhaseSpectrum, this, std::placeholders::_1, std::placeholders::_2));
    registerExportHandler(DataSpecificationGW::SPECTRUM_CODE_AE_PULSE,
                         std::bind(&SpectrumExporter::exportAEPulseSpectrum, this, std::placeholders::_1, std::placeholders::_2));
    registerExportHandler(DataSpecificationGW::SPECTRUM_CODE_AE_WAVE,
                         std::bind(&SpectrumExporter::exportAEWaveSpectrum, this, std::placeholders::_1, std::placeholders::_2));
    registerExportHandler(DataSpecificationGW::SPECTRUM_CODE_TEV_AMP,
                         std::bind(&SpectrumExporter::exportTEVAmpSpectrum, this, std::placeholders::_1, std::placeholders::_2));
    registerExportHandler(DataSpecificationGW::SPECTRUM_CODE_HFCT_PRPD,
                         std::bind(&SpectrumExporter::exportPRPDSpectrum, this, std::placeholders::_1, std::placeholders::_2));
    registerExportHandler(DataSpecificationGW::SPECTRUM_CODE_UHF_PRPD,
                         std::bind(&SpectrumExporter::exportPRPDSpectrum, this, std::placeholders::_1, std::placeholders::_2));
    registerExportHandler(DataSpecificationGW::SPECTRUM_CODE_HFCT_PRPS,
                         std::bind(&SpectrumExporter::exportPRPSSpectrum, this, std::placeholders::_1, std::placeholders::_2));
    registerExportHandler(DataSpecificationGW::SPECTRUM_CODE_UHF_PRPS,
                         std::bind(&SpectrumExporter::exportPRPSSpectrum, this, std::placeholders::_1, std::placeholders::_2));
    registerExportHandler(DataSpecificationGW::SPECTRUM_CODE_INFRARED,
                         std::bind(&SpectrumExporter::exportInfraredSpectrum, this, std::placeholders::_1, std::placeholders::_2));
}

bool SpectrumExporter::exportToFile(const QString& filePath, 
                                  DataSpecificationGW::DataSpecification* specification, 
                                  ExportFormat format, 
                                  const ExportOptions& options)
{
    if (!specification) {
        return false;
    }

    bool success = false;

    switch (format) {
        case CSV:
            success = exportToCSVFile(filePath, specification, options);
            break;
        case EXCEL:
            // Excel格式通过CSV转换，使用特定分隔符
            {
                ExportOptions excelOptions = options;
                // Excel特定设置可以在这里添加
                success = exportToCSVFile(filePath, specification, excelOptions);
            }
            break;
        case JSON:
            success = exportToJSONFile(filePath, specification);
            break;
        case XML:
            success = exportToXMLFile(filePath, specification);
            break;
        default:
            // 不支持的格式
            success = false;
            break;
    }

    if (success) {
        emit progressUpdated(100, QString("导出到 %1 成功").arg(filePath));
    } else {
        emit progressUpdated(100, QString("导出到 %1 失败").arg(filePath));
    }

    return success;
}

// 添加CSV格式特殊字符处理函数
QString SpectrumExporter::escapeCSVField(const QString& field)
{
    if (field.isEmpty()) {
        return QString();
    }
    
    // 如果字段包含逗号、引号或换行符，需要用引号包裹并转义引号
    if (field.contains(',') || field.contains('"') || field.contains('\n') || field.contains('\r')) {
        QString escaped = field;
        escaped.replace("\"", "\"\"");
        return "\"" + escaped + "\"";
    }
    return field;
}

// 辅助函数：将二进制数据转换为十六进制字符串
QString SpectrumExporter::binaryToHexString(const QByteArray& data, int maxLength)
{
    if (data.isEmpty()) {
        return QString("(空)");
    }
    
    // 限制长度
    QByteArray displayData = (maxLength >= 0 && data.size() > maxLength) ? 
                            data.left(maxLength) : data;
    
    QString hexString;
    for (int i = 0; i < displayData.size(); ++i) {
        hexString += QString("%1 ").arg(static_cast<uchar>(displayData.at(i)), 2, 16, QChar('0'));
        
        // 每16个字节换行
        if ((i + 1) % 16 == 0) {
            hexString += "\n";
        }
    }
    
    if (maxLength >= 0 && data.size() > maxLength) {
        hexString += QString("\n... (共 %1 字节)").arg(data.size());
    }
    
    return hexString.trimmed();
}

QString SpectrumExporter::binaryToBase64(const QByteArray& data)
{
    if (data.isEmpty()) {
        return QString("(空)");
    }
    
    return data.toBase64();
}

bool SpectrumExporter::exportToCSV(QTextStream& out, DataSpecificationGW::DataSpecification* specification)
{
    if (!specification) {
        return false;
    }

    // 导出文件头
    if (!exportFileHeader(out, specification)) {
        return false;
    }

    // 获取图谱数量
    DataSpecificationGW::SpectrumDataFileHead fileHead;
    specification->getSpectrumDataFileHead(fileHead);
    int spectrumCount = fileHead.sSpectrumCount;

    // 导出每个图谱
    for (int i = 0; i < spectrumCount; i++) {
        DataSpecificationGW::Spectrum* spectrum = specification->spectrum(i);
        if (!spectrum) {
            continue;
        }

        // 导出图谱头信息
        out << "## 图谱 " << (i + 1) << "\n";
        if (!exportSpectrumHeader(out, spectrum)) {
            return false;
        }

        // 根据图谱类型导出不同的数据
        DataSpecificationGW::SpectrumHead head;
        spectrum->getSpectrumHead(head);
        
        bool result = false;
        switch (head.eSpectrumTypeCode) {
            case DataSpecificationGW::SPECTRUM_CODE_AE_AMP:
                result = exportAEAmpSpectrum(out, spectrum);
                break;
            case DataSpecificationGW::SPECTRUM_CODE_AE_PHASE:
                result = exportAEPhaseSpectrum(out, spectrum);
                break;
            case DataSpecificationGW::SPECTRUM_CODE_AE_PULSE:
                result = exportAEPulseSpectrum(out, spectrum);
                break;
            case DataSpecificationGW::SPECTRUM_CODE_AE_WAVE:
                result = exportAEWaveSpectrum(out, spectrum);
                break;
            case DataSpecificationGW::SPECTRUM_CODE_TEV_AMP:
                result = exportTEVAmpSpectrum(out, spectrum);
                break;
            case DataSpecificationGW::SPECTRUM_CODE_HFCT_PRPD:
            case DataSpecificationGW::SPECTRUM_CODE_UHF_PRPD:
                result = exportPRPDSpectrum(out, spectrum);
                break;
            case DataSpecificationGW::SPECTRUM_CODE_HFCT_PRPS:
            case DataSpecificationGW::SPECTRUM_CODE_UHF_PRPS:
                result = exportPRPSSpectrum(out, spectrum);
                break;
            case DataSpecificationGW::SPECTRUM_CODE_INFRARED:
                result = exportInfraredSpectrum(out, spectrum);
                break;
            default:
                // 对于未知的图谱类型，导出通用信息
                out << "# 未知图谱类型: " << static_cast<int>(head.eSpectrumTypeCode) << "\n";
                result = true;
                break;
        }

        if (!result) {
            return false;
        }

        // 更新进度
        m_currentSpectrumIndex++;
        int progress = static_cast<int>(static_cast<double>(m_currentSpectrumIndex) / m_totalSpectrumCount * 100);
        emit progressUpdated(progress, QString("导出图谱 %1/%2").arg(m_currentSpectrumIndex).arg(m_totalSpectrumCount));
    }

    return true;
}

bool SpectrumExporter::exportToJSON(QTextStream& out, DataSpecificationGW::DataSpecification* specification)
{
    if (!specification) {
        out << "{\n";
        out << "  \"error\": \"无效的数据规范对象\"\n";
        out << "}\n";
        return false;
    }

    // TODO: 实现JSON格式导出
    out << "{\n";
    out << "  \"error\": \"JSON导出功能尚未实现\",\n";
    out << "  \"specification\": {\n";
    out << "    \"version\": \"" << specification->dataSpecificationVersion() << "\"\n";
    out << "  }\n";
    out << "}\n";
    return false;
}

bool SpectrumExporter::exportToXML(QTextStream& out, DataSpecificationGW::DataSpecification* specification)
{
    if (!specification) {
        out << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
        out << "<error>无效的数据规范对象</error>\n";
        return false;
    }

    // TODO: 实现XML格式导出
    out << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    out << "<error>XML导出功能尚未实现</error>\n";
    out << "<specification version=\"" << specification->dataSpecificationVersion() << "\"/>\n";
    return false;
}

SpectrumExporter *SpectrumExporter::instance()
{
    static SpectrumExporter instance;
    return &instance;
}

// 创建CSV表头
QList<QString> SpectrumExporter::createCSVHeader(DataSpecificationGW::DataSpecification* specification)
{
    // 返回空表头，因为我们已经在数据中添加了标题信息
    return QList<QString>();
}

// 将DataSpecification转换为CSV数据对象
QtCSV::StringData SpectrumExporter::convertToCSVData(DataSpecificationGW::DataSpecification* specification, 
                                                   const ExportOptions& options)
{
    if (!specification) {
        return QtCSV::StringData();
    }

    QtCSV::StringData csvData;

    // 添加UTF-8 BOM
    if (options.addBOM) {
        QList<QString> bom;
        bom << QString::fromUtf8("\xEF\xBB\xBF");
        csvData.addRow(bom);
    }

    // 获取文件头信息
    DataSpecificationGW::SpectrumDataFileHead fileHead;
    specification->getSpectrumDataFileHead(fileHead);

    // 添加文件信息
    if (options.exportFileHeader) {
        csvData.addRow(QList<QString>() << "# 图谱数据文件");
        csvData.addRow(QList<QString>() << QString("数据规范版本: %1").arg(fileHead.qstrVersion));
        csvData.addRow(QList<QString>() << QString("图谱数量: %1").arg(fileHead.sSpectrumCount));
        csvData.addRow(QList<QString>() << QString("文件创建时间: %1").arg(formatDateTime(fileHead.qstrGenerationTime)));
        csvData.addRow(QList<QString>() << QString("站点名称: %1").arg(fileHead.qstrStationName));
        csvData.addRow(QList<QString>() << QString("站点编码: %1").arg(fileHead.qstrStationCode));
        csvData.addRow(QList<QString>() << QString("仪器制造商: %1").arg(fileHead.qstrInstrumentManufacturer));
        csvData.addRow(QList<QString>() << QString("仪器型号: %1").arg(fileHead.qstrInstrumentModel));
        csvData.addRow(QList<QString>() << QString("仪器版本: %1").arg(fileHead.qstrInstrumentVersion));
        csvData.addRow(QList<QString>() << QString("仪器序列号: %1").arg(fileHead.qstrInstrumentSerialNumber));
        csvData.addRow(QList<QString>() << QString("系统频率: %1").arg(fileHead.fSystemFrequency));
        csvData.addRow(QList<QString>() << QString("公司代码: %1").arg(fileHead.qstrCompanyCode));
        csvData.addEmptyRow();
    }

    int iSpectrumCount = fileHead.sSpectrumCount;
    
    if (iSpectrumCount <= 0) {
        csvData.addRow(QList<QString>() << "# 无图谱数据");
        return csvData;
    }

    // 添加每个图谱的数据
    for (int i = 0; i < iSpectrumCount; i++) {
        emit progressUpdated(i * 100 / iSpectrumCount, QString("正在导出第 %1/%2 个图谱...").arg(i + 1).arg(iSpectrumCount));
        
        DataSpecificationGW::Spectrum* spectrum = specification->spectrum(i);
        if (spectrum) {
            // 获取图谱头信息
            DataSpecificationGW::SpectrumHead head;
            spectrum->getSpectrumHead(head);
            
            // 如果指定了图谱类型过滤，检查当前图谱是否需要导出
            if (!options.spectrumTypes.isEmpty() && 
                !options.spectrumTypes.contains(head.eSpectrumTypeCode)) {
                continue;
            }
            
            // 添加图谱标题
            csvData.addRow(QList<QString>() << QString("## 图谱 %1").arg(i + 1));
            
            // 添加图谱数据
            addSpectrumToCSVData(csvData, spectrum, options);
            
            csvData.addEmptyRow();
        }
    }

    emit progressUpdated(100, "导出完成");
    
    return csvData;
}

// 添加图谱数据到CSV数据对象
bool SpectrumExporter::addSpectrumToCSVData(QtCSV::StringData& data, 
                                          DataSpecificationGW::Spectrum* spectrum,
                                          const ExportOptions& options)
{
    if (!spectrum) {
        data.addRow(QList<QString>() << "# 错误: 无效的图谱对象");
        return false;
    }
    
    // 获取图谱头信息
    DataSpecificationGW::SpectrumHead head;
    spectrum->getSpectrumHead(head);
    
    // 添加图谱基本信息
    if (options.exportSpectrumBasicInfo) {
        data.addRow(QList<QString>() << "### 图谱基本信息");
        data.addRow(QList<QString>() << QString("图谱类型代码: %1").arg(static_cast<int>(head.eSpectrumTypeCode)));
        data.addRow(QList<QString>() << QString("图谱数据长度: %1").arg(head.iSpectrumDataLength));
        data.addRow(QList<QString>() << QString("图谱时间: %1").arg(formatDateTime(head.qstrSpectrumGenerationTime)));
        data.addRow(QList<QString>() << QString("图谱特性: %1").arg(static_cast<int>(head.eSpectrumCharacter)));
        data.addRow(QList<QString>() << QString("设备名称: %1").arg(head.qstrEquipmentName));
        data.addRow(QList<QString>() << QString("设备编码: %1").arg(head.qstrEquipmentCode));
        data.addRow(QList<QString>() << QString("测试点名称: %1").arg(head.qstrTestPointName));
        data.addRow(QList<QString>() << QString("测试点编码: %1").arg(head.qstrTestPointCode));
        data.addRow(QList<QString>() << QString("检测通道ID: %1").arg(head.sDetectionChannelID));
        data.addRow(QList<QString>() << QString("存储数据类型: %1").arg(static_cast<int>(head.eStorageDataType)));
        
        data.addEmptyRow();
    }
    
    // 如果不需要导出扩展信息，直接返回
    if (!options.exportSpectrumExtInfo) {
        return true;
    }
    
    // 根据图谱类型添加不同的数据
    bool result = false;
    switch (head.eSpectrumTypeCode) {
        case DataSpecificationGW::SPECTRUM_CODE_AE_AMP:
            result = addAEAmpSpectrumData(data, spectrum, options);
            break;
        case DataSpecificationGW::SPECTRUM_CODE_AE_PHASE:
            result = addAEPhaseSpectrumData(data, spectrum, options);
            break;
        case DataSpecificationGW::SPECTRUM_CODE_AE_PULSE:
            result = addAEPulseSpectrumData(data, spectrum, options);
            break;
        case DataSpecificationGW::SPECTRUM_CODE_AE_WAVE:
            result = addAEWaveSpectrumData(data, spectrum, options);
            break;
        case DataSpecificationGW::SPECTRUM_CODE_TEV_AMP:
            result = addTEVAmpSpectrumData(data, spectrum, options);
            break;
        case DataSpecificationGW::SPECTRUM_CODE_HFCT_PRPD:
        case DataSpecificationGW::SPECTRUM_CODE_UHF_PRPD:
            result = addPRPDSpectrumData(data, spectrum, options);
            break;
        case DataSpecificationGW::SPECTRUM_CODE_HFCT_PRPS:
        case DataSpecificationGW::SPECTRUM_CODE_UHF_PRPS:
            result = addPRPSSpectrumData(data, spectrum, options);
            break;
        case DataSpecificationGW::SPECTRUM_CODE_INFRARED:
            result = addInfraredSpectrumData(data, spectrum, options);
            break;
        default:
            // 对于未知的图谱类型，添加通用信息
            data.addRow(QList<QString>() << QString("# 未知图谱类型: %1").arg(static_cast<int>(head.eSpectrumTypeCode)));
            result = true;
            break;
    }
    
    return result;
}

// 添加AE幅值图谱数据到CSV数据对象
bool SpectrumExporter::addAEAmpSpectrumData(QtCSV::StringData& data, 
                                          DataSpecificationGW::Spectrum* spectrum,
                                          const ExportOptions& options)
{
    // 转换为AE幅值图谱
    DataSpecificationGW::AEAmpSpectrum* aeAmpSpectrum = 
        dynamic_cast<DataSpecificationGW::AEAmpSpectrum*>(spectrum);
    
    if (!aeAmpSpectrum) {
        data.addRow(QList<QString>() << "# 错误: 图谱类型转换失败");
        return false;
    }
    
    // 获取AE幅值扩展信息
    DataSpecificationGW::AEAmpExtInformation extInfo;
    aeAmpSpectrum->getAEAmpExtInformation(extInfo);
    
    // 添加AE幅值特有信息
    data.addRow(QList<QString>() << "### AE幅值特有信息");
    
    // 添加表头
    QList<QString> header;
    header << "幅值单位" << "幅值下限" << "幅值上限" << "频带" << "频率下限" << "频率上限";
    data.addRow(header);
    
    // 添加数据行
    QList<QString> row;
    row << QString::number(static_cast<int>(extInfo.eAmpUnit));
    row << QString::number(extInfo.fAmpLowerLimit);
    row << QString::number(extInfo.fAmpUpperLimit);
    row << QString::number(static_cast<int>(extInfo.eFrequencyBand));
    row << QString::number(extInfo.fFrequencyLowerLimit);
    row << QString::number(extInfo.fFequencyUpperLimit);
    
    data.addRow(row);
    data.addEmptyRow();
    
    // 获取AE幅值数据
    DataSpecificationGW::AEAmpData aeData;
    aeAmpSpectrum->getAEAmpData(aeData);
    
    // 添加AE幅值数据
    data.addRow(QList<QString>() << "### AE幅值数据");
    
    // 添加表头
    header.clear();
    header << "信号最大值" << "信号有效值" << "频率分量1" << "频率分量2" 
           << "背景信号最大值" << "背景信号有效值" << "背景频率分量1" << "背景频率分量2";
    data.addRow(header);
    
    // 添加数据行
    row.clear();
    row << QString::number(aeData.fSignalMax);
    row << QString::number(aeData.fSignalRMS);
    row << QString::number(aeData.fFrequencyComponent1);
    row << QString::number(aeData.fFrequencyComponent2);
    row << QString::number(aeData.fBGSignalMax);
    row << QString::number(aeData.fBGSignalRMS);
    row << QString::number(aeData.fBGFrequencyComponent1);
    row << QString::number(aeData.fBGFrequencyComponent2);
    
    data.addRow(row);
    
    return true;
}

// 添加AE相位图谱数据到CSV数据对象
bool SpectrumExporter::addAEPhaseSpectrumData(QtCSV::StringData& data, 
                                          DataSpecificationGW::Spectrum* spectrum,
                                          const ExportOptions& options)
{
    // 转换为AE相位图谱
    DataSpecificationGW::AEPhaseSpectrum* aePhaseSpectrum = 
        dynamic_cast<DataSpecificationGW::AEPhaseSpectrum*>(spectrum);
    
    if (!aePhaseSpectrum) {
        data.addRow(QList<QString>() << "# 错误: 图谱类型转换失败");
        return false;
    }
    
    // 获取AE相位扩展信息
    DataSpecificationGW::AEPhaseExtInformation extInfo;
    aePhaseSpectrum->getAEPhaseExtInformation(extInfo);
    
    // 添加AE相位特有信息
    data.addRow(QList<QString>() << "### AE相位特有信息");
    
    // 添加表头
    QList<QString> header;
    header << "幅值单位" << "幅值下限" << "幅值上限" << "相位窗数" << "量化幅值" << "同步频率";
    data.addRow(header);
    
    // 添加数据行
    QList<QString> row;
    row << QString::number(static_cast<int>(extInfo.eAmpUnit));
    row << QString::number(extInfo.fAmpLowerLimit);
    row << QString::number(extInfo.fAmpUpperLimit);
    row << QString::number(extInfo.iDataPoint);
    row << QString::number(extInfo.fTriggerThreshold);
    row << QString::number(extInfo.fSyncFrequency);
    
    data.addRow(row);
    data.addEmptyRow();
    
    // 获取AE相位数据
    DataSpecificationGW::AEPhaseData aeData;
    aePhaseSpectrum->getAEPhaseData(aeData);
    
    // 添加AE相位数据
    data.addRow(QList<QString>() << "### AE相位数据");
    data.addRow(QList<QString>() << QString("相位数据大小: %1 字节").arg(aeData.qbaAEPhaseData.size()));
    
    // 添加表头
    header.clear();
    header << "相位" << "幅值";
    data.addRow(header);
    
    // 根据二进制数据导出选项处理
    if (!aeData.qbaAEPhaseData.isEmpty()) {
        switch (options.binaryOption) {
            case HEXSTRING_FULL:
                data.addRow(QList<QString>() << "十六进制表示(完整):");
                data.addRow(QList<QString>() << binaryToHexString(aeData.qbaAEPhaseData, -1));
                break;
            case BASE64_FULL:
                data.addRow(QList<QString>() << "Base64编码(完整):");
                data.addRow(QList<QString>() << binaryToBase64(aeData.qbaAEPhaseData));
                break;
            case NONE:
                data.addRow(QList<QString>() << "# 二进制数据已忽略");
                break;
            case HEXSTRING_SHORT:
            default:
                data.addRow(QList<QString>() << "十六进制表示(前50字节):");
                data.addRow(QList<QString>() << binaryToHexString(aeData.qbaAEPhaseData, 50));
                break;
        }
    } else {
        data.addRow(QList<QString>() << "# 无AE相位数据");
    }
    
    return true;
}

// 添加AE脉冲图谱数据到CSV数据对象
bool SpectrumExporter::addAEPulseSpectrumData(QtCSV::StringData& data, 
                                          DataSpecificationGW::Spectrum* spectrum,
                                          const ExportOptions& options)
{
    // 转换为AE脉冲图谱
    DataSpecificationGW::AEPulseSpectrum* aePulseSpectrum = 
        dynamic_cast<DataSpecificationGW::AEPulseSpectrum*>(spectrum);
    
    if (!aePulseSpectrum) {
        data.addRow(QList<QString>() << "# 错误: 图谱类型转换失败");
        return false;
    }
    
    // 获取AE脉冲扩展信息
    DataSpecificationGW::AEPulseExtInformation extInfo;
    aePulseSpectrum->getAEPulseExtInformation(extInfo);
    
    // 添加AE脉冲特有信息
    data.addRow(QList<QString>() << "### AE脉冲特有信息");
    
    // 添加表头
    QList<QString> header;
    header << "幅值下限" << "幅值上限" << "采样点数" << "触发阈值" << "同步频率";
    data.addRow(header);
    
    // 添加数据行
    QList<QString> row;
    row << QString::number(extInfo.fAmpLowerLimit);
    row << QString::number(extInfo.fAmpUpperLimit);
    row << QString::number(extInfo.iDataPoint);
    row << QString::number(extInfo.fTriggerThreshold);
    row << QString::number(extInfo.fSyncFrequency);
    
    data.addRow(row);
    data.addEmptyRow();
    
    // 获取AE脉冲数据
    DataSpecificationGW::AEPulseData aeData;
    aePulseSpectrum->getAEPulseData(aeData);
    
    // 添加AE脉冲数据
    data.addRow(QList<QString>() << "### AE脉冲数据");
    data.addRow(QList<QString>() << QString("脉冲数据大小: %1 字节").arg(aeData.qbaAEPulseData.size()));
    
    // 根据二进制数据导出选项处理
    if (!aeData.qbaAEPulseData.isEmpty()) {
        switch (options.binaryOption) {
            case HEXSTRING_FULL:
                data.addRow(QList<QString>() << "十六进制表示(完整):");
                data.addRow(QList<QString>() << binaryToHexString(aeData.qbaAEPulseData, -1));
                break;
            case BASE64_FULL:
                data.addRow(QList<QString>() << "Base64编码(完整):");
                data.addRow(QList<QString>() << binaryToBase64(aeData.qbaAEPulseData));
                break;
            case NONE:
                data.addRow(QList<QString>() << "# 二进制数据已忽略");
                break;
            case HEXSTRING_SHORT:
            default:
                data.addRow(QList<QString>() << "十六进制表示(前50字节):");
                data.addRow(QList<QString>() << binaryToHexString(aeData.qbaAEPulseData, 50));
                break;
        }
    } else {
        data.addRow(QList<QString>() << "# 无AE脉冲数据");
    }
    
    return true;
}

// 添加AE波形图谱数据到CSV数据对象
bool SpectrumExporter::addAEWaveSpectrumData(QtCSV::StringData& data, 
                                          DataSpecificationGW::Spectrum* spectrum,
                                          const ExportOptions& options)
{
    // 转换为AE波形图谱
    DataSpecificationGW::AEWaveSpectrum* aeWaveSpectrum = 
        dynamic_cast<DataSpecificationGW::AEWaveSpectrum*>(spectrum);
    
    if (!aeWaveSpectrum) {
        data.addRow(QList<QString>() << "# 错误: 图谱类型转换失败");
        return false;
    }
    
    // 获取AE波形扩展信息
    DataSpecificationGW::AEWaveExtInformation extInfo;
    aeWaveSpectrum->getAEWaveExtInformation(extInfo);
    
    // 添加AE波形特有信息
    data.addRow(QList<QString>() << "### AE波形特有信息");
    
    // 添加表头
    QList<QString> header;
    header << "采样率" << "采样点数" << "量化位数" << "同步频率";
    data.addRow(header);
    
    // 添加数据行
    QList<QString> row;
    row << QString::number(extInfo.llSampleRate);
    row << QString::number(extInfo.iDataPoint);
    row << QString::number(extInfo.fTriggerThreshold);
    row << QString::number(extInfo.fSyncFrequency);
    
    data.addRow(row);
    data.addEmptyRow();
    
    // 获取AE波形数据
    DataSpecificationGW::AEWaveData aeData;
    aeWaveSpectrum->getAEWaveData(aeData);
    
    // 添加AE波形数据
    data.addRow(QList<QString>() << "### AE波形数据");
    data.addRow(QList<QString>() << QString("波形数据大小: %1 字节").arg(aeData.qbaAEWaveData.size()));
    
    // 添加二进制数据的十六进制表示
    if (!aeData.qbaAEWaveData.isEmpty()) {
        data.addRow(QList<QString>() << "前50字节十六进制表示:");
        data.addRow(QList<QString>() << binaryToHexString(aeData.qbaAEWaveData));
    } else {
        data.addRow(QList<QString>() << "# 无AE波形数据");
    }
    
    return true;
}

// 添加TEV幅值图谱数据到CSV数据对象
bool SpectrumExporter::addTEVAmpSpectrumData(QtCSV::StringData& data, 
                                          DataSpecificationGW::Spectrum* spectrum,
                                          const ExportOptions& options)
{
    // 转换为TEV幅值图谱
    DataSpecificationGW::TEVAmpSpectrum* tevAmpSpectrum = 
        dynamic_cast<DataSpecificationGW::TEVAmpSpectrum*>(spectrum);
    
    if (!tevAmpSpectrum) {
        data.addRow(QList<QString>() << "# 错误: 图谱类型转换失败");
        return false;
    }
    
    // 获取TEV幅值扩展信息
    DataSpecificationGW::TEVAmpExtInformation extInfo;
    tevAmpSpectrum->getTEVAmpExtInformation(extInfo);
    
    // 添加TEV幅值特有信息
    data.addRow(QList<QString>() << "### TEV幅值特有信息");
    
    // 添加表头
    QList<QString> header;
    header << "幅值单位" << "幅值下限" << "幅值上限";
    data.addRow(header);
    
    // 添加数据行
    QList<QString> row;
    row << QString::number(static_cast<int>(extInfo.eAmpUnit));
    row << QString::number(extInfo.fAmpLowerLimit);
    row << QString::number(extInfo.fAmpUpperLimit);
    
    data.addRow(row);
    data.addEmptyRow();
    
    // 获取TEV幅值数据
    DataSpecificationGW::TEVAmpData tevData;
    tevAmpSpectrum->getTEVAmpData(tevData);
    
    // 添加TEV幅值数据
    data.addRow(QList<QString>() << "### TEV幅值数据");
    
    // 添加表头
    header.clear();
    header << "TEV幅值" << "TEV最大值" << "脉冲数" << "严重程度" << "背景文件名" << "报警等级";
    data.addRow(header);
    
    // 添加数据行
    row.clear();
    row << QString::number(tevData.fTEVAmpValue);
    row << QString::number(tevData.fTEVMaxValue);
    row << QString::number(tevData.iPulseCount);
    row << QString::number(tevData.fSeverity);
    row << tevData.qstrBGFileName;
    row << QString::number(static_cast<int>(tevData.eDischargeSeverity));
    
    data.addRow(row);
    
    return true;
}

// 添加PRPD图谱数据到CSV数据对象
bool SpectrumExporter::addPRPDSpectrumData(QtCSV::StringData& data, 
                                          DataSpecificationGW::Spectrum* spectrum,
                                          const ExportOptions& options)
{
    // 转换为PRPD图谱
    DataSpecificationGW::PRPDSpectrum* prpdSpectrum = 
        dynamic_cast<DataSpecificationGW::PRPDSpectrum*>(spectrum);
    
    if (!prpdSpectrum) {
        data.addRow(QList<QString>() << "# 错误: 图谱类型转换失败");
        return false;
    }
    
    // 获取PRPD扩展信息
    DataSpecificationGW::PRPDExtInformation extInfo;
    prpdSpectrum->getPRPDExtInformation(extInfo);
    
    // 添加PRPD特有信息
    data.addRow(QList<QString>() << "### PRPD特有信息");
    
    // 添加表头
    QList<QString> header;
    header << "幅值单位" << "幅值下限" << "幅值上限" << "频带" << "频率下限" << "频率上限" 
           << "相位窗数" << "量化幅值" << "工频周期数";
    data.addRow(header);
    
    // 添加数据行
    QList<QString> row;
    row << QString::number(static_cast<int>(extInfo.eAmpUnit));
    row << QString::number(extInfo.fAmpLowerLimit);
    row << QString::number(extInfo.fAmpUpperLimit);
    row << QString::number(static_cast<int>(extInfo.eFrequencyBand));
    row << QString::number(extInfo.fFrequencyLowerLimit);
    row << QString::number(extInfo.fFequencyUpperLimit);
    row << QString::number(extInfo.iPhaseWindowCount);
    row << QString::number(extInfo.iQuantizedAmplitude);
    row << QString::number(extInfo.iPowerFreqCycleCount);
    
    data.addRow(row);
    data.addEmptyRow();
    
    // 添加放电类型概率
    data.addRow(QList<QString>() << "### 放电类型概率");
    
    // 添加表头
    header.clear();
    header << "类型1" << "类型2" << "类型3" << "类型4" << "类型5" << "类型6" << "类型7" << "类型8";
    data.addRow(header);
    
    // 添加数据行
    row.clear();
    row << QString::number(extInfo.aucPDTypeProbability[0]);
    row << QString::number(extInfo.aucPDTypeProbability[1]);
    row << QString::number(extInfo.aucPDTypeProbability[2]);
    row << QString::number(extInfo.aucPDTypeProbability[3]);
    row << QString::number(extInfo.aucPDTypeProbability[4]);
    row << QString::number(extInfo.aucPDTypeProbability[5]);
    row << QString::number(extInfo.aucPDTypeProbability[6]);
    row << QString::number(extInfo.aucPDTypeProbability[7]);
    
    data.addRow(row);
    data.addEmptyRow();
    
    // 添加其他信息
    data.addRow(QList<QString>() << "### 其他信息");
    
    // 添加表头
    header.clear();
    header << "背景文件名" << "数据判断标志" << "增益" << "同步源" << "同步状态" << "同步频率" << "报警等级" << "去噪阈值";
    data.addRow(header);
    
    // 添加数据行
    row.clear();
    row << extInfo.qstrBGFileName;
    row << QString::number(static_cast<int>(extInfo.eDataJudgmentFlag));
    row << QString::number(extInfo.sGain);
    row << QString::number(static_cast<int>(extInfo.eSyncSource));
    row << QString::number(extInfo.ucSyncState);
    row << QString::number(extInfo.fSyncFrequency);
    row << QString::number(static_cast<int>(extInfo.eDischargeSeverity));
    row << QString::number(extInfo.ucDenoisingThreshold);
    
    data.addRow(row);
    data.addEmptyRow();
    
    // 获取PRPD数据
    DataSpecificationGW::PRPDData prpdData;
    prpdSpectrum->getPRPDData(prpdData);
    
    // 添加PRPD数据
    data.addRow(QList<QString>() << "### PRPD数据 (二进制数据摘要)");
    data.addRow(QList<QString>() << QString("数据大小: %1 字节").arg(prpdData.qbaPDSpectrumData.size()));
    
    // 添加二进制数据的十六进制表示
    if (!prpdData.qbaPDSpectrumData.isEmpty()) {
        data.addRow(QList<QString>() << "前50字节十六进制表示:");
        data.addRow(QList<QString>() << binaryToHexString(prpdData.qbaPDSpectrumData));
    } else {
        data.addRow(QList<QString>() << "# 无PRPD数据");
    }
    
    return true;
}

// 添加PRPS图谱数据到CSV数据对象
bool SpectrumExporter::addPRPSSpectrumData(QtCSV::StringData& data, 
                                          DataSpecificationGW::Spectrum* spectrum,
                                          const ExportOptions& options)
{
    // 转换为PRPS图谱
    DataSpecificationGW::PRPSSpectrum* prpsSpectrum = 
        dynamic_cast<DataSpecificationGW::PRPSSpectrum*>(spectrum);
    
    if (!prpsSpectrum) {
        data.addRow(QList<QString>() << "# 错误: 图谱类型转换失败");
        return false;
    }
    
    // 获取PRPS扩展信息
    DataSpecificationGW::PRPSExtInformation extInfo;
    prpsSpectrum->getPRPSExtInformation(extInfo);
    
    // 添加PRPS特有信息
    data.addRow(QList<QString>() << "### PRPS特有信息");
    
    // 添加表头
    QList<QString> header;
    header << "幅值单位" << "幅值下限" << "幅值上限" << "频带" << "频率下限" << "频率上限" 
           << "相位窗数" << "量化幅值" << "工频周期数";
    data.addRow(header);
    
    // 添加数据行
    QList<QString> row;
    row << QString::number(static_cast<int>(extInfo.eAmpUnit));
    row << QString::number(extInfo.fAmpLowerLimit);
    row << QString::number(extInfo.fAmpUpperLimit);
    row << QString::number(static_cast<int>(extInfo.eFrequencyBand));
    row << QString::number(extInfo.fFrequencyLowerLimit);
    row << QString::number(extInfo.fFequencyUpperLimit);
    row << QString::number(extInfo.iPhaseWindowCount);
    row << QString::number(extInfo.iQuantizedAmplitude);
    row << QString::number(extInfo.iPowerFreqCycleCount);
    
    data.addRow(row);
    data.addEmptyRow();
    
    // 添加放电类型概率
    data.addRow(QList<QString>() << "### 放电类型概率");
    
    // 添加表头
    header.clear();
    header << "类型1" << "类型2" << "类型3" << "类型4" << "类型5" << "类型6" << "类型7" << "类型8";
    data.addRow(header);
    
    // 添加数据行
    row.clear();
    row << QString::number(extInfo.aucPDTypeProbability[0]);
    row << QString::number(extInfo.aucPDTypeProbability[1]);
    row << QString::number(extInfo.aucPDTypeProbability[2]);
    row << QString::number(extInfo.aucPDTypeProbability[3]);
    row << QString::number(extInfo.aucPDTypeProbability[4]);
    row << QString::number(extInfo.aucPDTypeProbability[5]);
    row << QString::number(extInfo.aucPDTypeProbability[6]);
    row << QString::number(extInfo.aucPDTypeProbability[7]);
    
    data.addRow(row);
    data.addEmptyRow();
    
    // 添加其他信息
    data.addRow(QList<QString>() << "### 其他信息");
    
    // 添加表头
    header.clear();
    header << "背景文件名" << "数据判断标志" << "增益" << "同步源" << "同步状态" << "同步频率" << "报警等级" << "去噪阈值";
    data.addRow(header);
    
    // 添加数据行
    row.clear();
    row << extInfo.qstrBGFileName;
    row << QString::number(static_cast<int>(extInfo.eDataJudgmentFlag));
    row << QString::number(extInfo.sGain);
    row << QString::number(static_cast<int>(extInfo.eSyncSource));
    row << QString::number(extInfo.ucSyncState);
    row << QString::number(extInfo.fSyncFrequency);
    row << QString::number(static_cast<int>(extInfo.eDischargeSeverity));
    row << QString::number(extInfo.ucDenoisingThreshold);
    
    data.addRow(row);
    data.addEmptyRow();
    
    // 获取PRPS数据
    DataSpecificationGW::PRPSData prpsData;
    prpsSpectrum->getPRPSData(prpsData);
    
    // 添加PRPS数据
    data.addRow(QList<QString>() << "### PRPS数据 (二进制数据摘要)");
    data.addRow(QList<QString>() << QString("数据大小: %1 字节").arg(prpsData.qbaPDSpectrumData.size()));
    
    // 添加二进制数据的十六进制表示
    if (!prpsData.qbaPDSpectrumData.isEmpty()) {
        data.addRow(QList<QString>() << "前50字节十六进制表示:");
        data.addRow(QList<QString>() << binaryToHexString(prpsData.qbaPDSpectrumData));
    } else {
        data.addRow(QList<QString>() << "# 无PRPS数据");
    }
    
    return true;
}

// 添加红外图谱数据到CSV数据对象
bool SpectrumExporter::addInfraredSpectrumData(QtCSV::StringData& data, 
                                          DataSpecificationGW::Spectrum* spectrum,
                                          const ExportOptions& options)
{
    // 转换为红外图谱
    DataSpecificationGW::InfraredSpectrum* infraredSpectrum = 
        dynamic_cast<DataSpecificationGW::InfraredSpectrum*>(spectrum);
    
    if (!infraredSpectrum) {
        data.addRow(QList<QString>() << "# 错误: 图谱类型转换失败");
        return false;
    }
    
    // 获取红外扩展信息
    DataSpecificationGW::InfraredExtInformation extInfo;
    infraredSpectrum->getInfraredExtInformation(extInfo);
    
    // 添加红外特有信息
    data.addRow(QList<QString>() << "### 红外特有信息");
    
    // 添加表头
    QList<QString> header;
    header << "温度单位" << "环境温度";
    data.addRow(header);
    
    // 添加数据行
    QList<QString> row;
    row << QString::number(static_cast<int>(extInfo.eTemperatureUnit));
    row << QString::number(extInfo.fAtomTemperature);
    
    data.addRow(row);
    data.addEmptyRow();
    
    // 获取红外数据
    DataSpecificationGW::InfraredData irData;
    infraredSpectrum->getInfraredData(irData);
    
    // 添加红外数据
    data.addRow(QList<QString>() << "### 红外数据");
    data.addRow(QList<QString>() << QString("图像数据大小: %1 字节").arg(irData.qbaInfraredPhotoData.size()));
    data.addRow(QList<QString>() << QString("温度数据大小: %1 字节").arg(irData.qbaInfraredTemperatureData.size()));
    
    // 添加图像数据的十六进制表示
    if (!irData.qbaInfraredPhotoData.isEmpty()) {
        data.addRow(QList<QString>() << "图像数据前50字节十六进制表示:");
        data.addRow(QList<QString>() << binaryToHexString(irData.qbaInfraredPhotoData));
    } else {
        data.addRow(QList<QString>() << "# 无红外图像数据");
    }
    
    // 添加温度数据的十六进制表示
    if (!irData.qbaInfraredTemperatureData.isEmpty()) {
        data.addRow(QList<QString>() << "温度数据前50字节十六进制表示:");
        data.addRow(QList<QString>() << binaryToHexString(irData.qbaInfraredTemperatureData));
    } else {
        data.addRow(QList<QString>() << "# 无温度数据");
    }
    
    return true;
}

// 实现JSON和XML文件导出函数
bool SpectrumExporter::exportToJSONFile(const QString& filePath, DataSpecificationGW::DataSpecification* specification)
{
    if (!specification) return false;
    
    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        return false;
    }
    
    QTextStream out(&file);
    out.setCodec("UTF-8");
    
    bool success = exportToJSON(out, specification);
    
    file.close();
    return success;
}

bool SpectrumExporter::exportToXMLFile(const QString& filePath, DataSpecificationGW::DataSpecification* specification)
{
    if (!specification) return false;
    
    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        return false;
    }
    
    QTextStream out(&file);
    out.setCodec("UTF-8");
    
    bool success = exportToXML(out, specification);
    
    file.close();
    return success;
}

// 添加exportToCSVFile方法实现
bool SpectrumExporter::exportToCSVFile(const QString& filePath, 
                                     DataSpecificationGW::DataSpecification* specification,
                                     const ExportOptions& options)
{
    QtCSV::StringData csvData = convertToCSVData(specification, options);
    if (csvData.isEmpty()) {
        return false;
    }
    
    // 使用QtCSV库写入文件
    bool success = QtCSV::Writer::write(
        filePath,
        csvData,
        ",",           // 分隔符
        "\"",          // 文本分隔符
        QtCSV::Writer::WriteMode::REWRITE, 
        createCSVHeader(specification),  // 表头
        QList<QString>(),  // 无表尾
        "UTF-8"        // 编码 - 使用字符串而非QTextCodec指针
    );
    
    return success;
}
